package dao;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class BaseSql<T> {
	private Class<T>  entity;
	private String tablename;
	private Connection conn;
	
	@SuppressWarnings("unchecked")
	public BaseSql() {
		ParameterizedType type=(ParameterizedType) this.getClass().getGenericSuperclass();
		entity=(Class<T>) type.getActualTypeArguments()[0];
		tablename=entity.getSimpleName();
		conn=DBUtil.getConnection();
	}
	
	public void insert(T o){
		StringBuffer sql=new StringBuffer("insert into "+tablename+"(");
		Field[] fd=entity.getDeclaredFields();
		for(int i=0;i<fd.length;i++){
			sql.append(fd[i].getName());
			if(i<fd.length-1) sql.append(",");
			else sql.append(") values(");
		}
		for(int i=0;i<fd.length;i++){
			sql.append("?");
			if(i<fd.length-1) sql.append(",");
			else sql.append(")");
		}
		System.out.println(sql.toString());
		try {
			PreparedStatement pstm=conn.prepareStatement(sql.toString());
			for(int i=0;i<fd.length;i++){
				fd[i].setAccessible(true);
				Object val=fd[i].get(o);
				pstm.setObject(i+1, val);
			}
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
